package com.muyi.controller;

import com.muyi.mapper.UserMapper;
import com.muyi.pojo.entity.Result;
import com.muyi.pojo.entity.User;
import com.muyi.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "登录模块")
@Slf4j
@RestController
@Tag(name = "登录模块", description = "登录相关接口")
public class LoginController {

    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        log.info("用户登录: {}", user);
        User e = userMapper.getByUsername(user);

        if (e == null) {
            throw new RuntimeException("用户不存在");
        }

        // 判断是否冻结
        if ("冻结".equals(e.getStatus())) {
            if (e.getLock_time() != null &&
                    LocalDateTime.now().isAfter(e.getLock_time().plusDays(7))) {
                // 解冻
                e.setStatus("正常");
                e.setError_count(0);
                e.setLock_time(null);
                userMapper.update(e);
            } else {
                throw new RuntimeException("账号已被冻结，请7天后再试");
            }
        }

        // 比较密码（实际应使用 BCrypt 等加密方式）
        if (!user.getPassword().equals(e.getPassword())) {
            int count = e.getError_count() + 1;
            e.setError_count(count);

            if (count >= 5) {
                e.setStatus("冻结");
                e.setLock_time(LocalDateTime.now());
            }

            userMapper.update(e);
            throw new RuntimeException("密码错误");
        }

        // 密码正确
        e.setError_count(0);
        userMapper.update(e);
        //登录成功,生成令牌,下发令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("user_id", e.getUser_id());
        claims.put("nickname", e.getNickname());

        String jwt = JwtUtils.generateJwt(claims); //jwt包含了当前登录的员工信息
        return Result.success(jwt);

    }
}
